package com.xhwl.data.initial;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.netflix.discovery.converters.Auto;
import com.xhwl.common.dto.cent.sdata.PermissionGroupDTO;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.data.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: luyi
 * @Description: 初始化开放平台后台帐号的角色
 *              1 添加管理员角色
 *              2 绑定管理员角色权限
 *              3 给admin帐号绑定管理员角色
 *              注：
 *              1 存在管理员角色不执行
 *              2 需要先有app数据，菜单数据，adminaccount帐号数据
 * @Date: Create in 14:41 2022/9/17
 */
@Component
@DependsOn("flywayInitializer")
public class OpenPlatformInitial {



    private static final Logger log = LoggerFactory.getLogger(OpenPlatformInitial.class);

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IAppService appService;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IAdminAccountRoleService adminAccountRoleService;

    @PostConstruct
    public void start(){
        log.info("开始初始化开放平台后台的管理员帐号");
        // 查询是否已经有后台管理的角色了
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("industry_id", 15);
        roleQueryWrapper.eq("code", "openadmin");
        roleQueryWrapper.eq("is_deleted", false);
        List<Role> list = roleService.list(roleQueryWrapper);
        if(!list.isEmpty()){
            log.info("管理员角色已经存在，初始化终止");
            return;
        }
        // 添加管理员角色
        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("app_id", "202207198542");
        App one = appService.getOne(appQueryWrapper);
        if(null == one){
            log.info("缺少app信息，请先执行脚本, 初始化终止");
            return;
        }

        Role role = new Role();
        role.setIndustryId((short)15);
        role.setName("管理员");
        role.setCode("openadmin");
        role.setGrade((short)2);
        role.setType(2);
        role.setIsInitialized(true);
        role.setLevel(1);
        role.setSortNum(1);
        role.setParentId(0);
        role.setStatus((short) 1);
        role.setIsDeleted(false);
        role.setAppId(one.getId());
        roleService.save(role);

        // 查询权限菜单
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        // 目前只有开放平台后台这一个app在15这个平台
        permissionQueryWrapper.eq("industry_id", 15);
        List<Permission> list1 = permissionService.list(permissionQueryWrapper);
        if(list1.isEmpty()){
            log.info("开放平台后台菜单不存在，需要先导入菜单，初始化终止");
            return;
        }
        // 给管理员角色增加权限
        List<RolePermission> rolePermissions = new ArrayList<>(list1.size());
        for (Permission permission : list1) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(permission.getId());
            rolePermissions.add(rolePermission);
        }


        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("login_name", "admin1");
        accountQueryWrapper.eq("is_deleted", false);
        // iam用户
        accountQueryWrapper.eq("type", 2);
        accountQueryWrapper.eq("develop_id", 25);
        Account account = null;
        try {
            account = accountService.getOne(accountQueryWrapper);
        }catch (Exception e){
            log.error("查询帐号 admin 失败， 初始化开放平台平台的权限终止");
            return;
        }
        if(null == account){
            log.info("缺少开放平台管理员帐号，现在创建");
            account = new Account();
            account.setLoginName("admin1");
            account.setPassword("user@123");
            account.setNickname("管理员");
            account.setName("管理员");
            account.setStatus((short)1);
            account.setIsDeleted(false);
            account.setDevelopId(25);
            // iam帐号
            account.setType((short) 2);
            AccountRelation accountRelation = new AccountRelation();
            accountRelation.setRoleIds(Arrays.asList(role.getId()));

            List<PermissionGroupDTO> permissionGroupDTOS = new ArrayList<>();
            PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
            permissionGroupDTO.setRoleIds(String.valueOf(role.getId()));
            permissionGroupDTO.setRoleList(Arrays.asList(role.getId()));
            permissionGroupDTOS.add(permissionGroupDTO);
            accountService.createAccountV2(account, accountRelation, permissionGroupDTOS);
            log.info("开放平台后台帐号角色初始化完成");
        }else{
            log.info("已经存在 login_name 为 admin1 的帐号， 开放平台初始化数据终止");
        }
    }
}
